package com.tgy.MyFlowable.workflow.service.impl;

import cn.hutool.core.convert.Convert;
import com.ctsi.core.common.util.$;
import com.ctsi.core.common.util.SecurityUtil;
import com.ctsi.workflow.service.IFlwCommonService;
import com.ctsi.workflow.service.IFlwEndTaskService;
import com.ctsi.workflow.util.BpmCommentUtil;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * @version 1.0
 * @author: wang xiao xiang
 * @date: 2021/8/8 19:32
 */
@Service
@RequiredArgsConstructor
public class FlwEndTaskServiceImpl implements IFlwEndTaskService {

    private final TaskService taskService;

    private final RuntimeService runtimeService;

    private final IFlwCommonService flwCommonService;

    @Autowired
    private HttpServletRequest request;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void end(String taskId, String comment) {
        //校验任务是否存在
        Task task = flwCommonService.queryTask(taskId);
        //获取流程实例id
        String processInstanceId = task.getProcessInstanceId();
        //获取当前操作人姓名
        String name = SecurityUtil.getUsername(request).getAccount();
        //生成终止意见
        comment = BpmCommentUtil.genEndComment(name, comment);
        //添加意见
        flwCommonService.addComment(taskId, comment);
        //获取当前操作人id
        //Long userId = MarsContextHolder.getUserId();
        Long userId = SecurityUtil.getUsername(request).getId();
        String assignee = task.getAssignee();
        if ($.isEmpty(assignee)) {
            //设置办理人为当前用户
            taskService.setAssignee(taskId, Convert.toStr(userId));
        }
        //结束流程
        runtimeService.deleteProcessInstance(processInstanceId, comment);
    }
}
